package com.bfly.mall.product.api;

import com.alibaba.fastjson.JSONObject;
import com.bfly.common.ResponseUtil;
import com.bfly.common.json.JsonUtil;
import com.bfly.common.page.Pager;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.context.PagerThreadLocal;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.mall.product.dto.ProductAttrDTO;
import com.bfly.mall.product.dto.ProductSecKillFormDTO;
import com.bfly.mall.product.dto.ProductSecKillListDTO;
import com.bfly.mall.product.entity.*;
import com.bfly.mall.product.enums.ProductActivityStatusEnum;
import com.bfly.mall.product.service.IProductSecKillService;
import com.bfly.mall.product.service.IProductService;
import com.bfly.mall.product.service.IProductSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品秒杀Controller
 *
 * @author 长沙商脉科技有限公司
 * @date 2021/2/16 11:19
 */
@RestController
@RequestMapping(value = "/api/product/seckill")
public class ProductSecKillApiController extends BaseController {

    @Autowired
    private IProductSecKillService productSecKillService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductSkuService productSkuService;

    /**
     * 秒杀产品列表
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/2/16 11:20
     */
    @GetMapping(value = "/list")
    public void list(HttpServletResponse response, HttpServletRequest request) {
        PagerThreadLocal.set(request);
        Map<String, Object> param = new HashMap<>();
        param.put("is_enabled", true);
        Map<String,Boolean> sortMap=new HashMap<>(2);
        sortMap.put("seq",true);
        sortMap.put("id",false);

        Pager<ProductSecKill> pager = productSecKillService.getPage(param,null,sortMap);
        Pager<ProductSecKillListDTO> dtoPager = new Pager<>(pager.getPageNo(), pager.getPageSize(), pager.getTotalCount());

        if (pager.getData() != null) {
            List<ProductSecKillListDTO> list = new ArrayList<>();
            for (ProductSecKill product : pager.getData()) {
                ProductSecKillListDTO dto = new ProductSecKillListDTO();
                BeanUtils.copyProperties(product, dto);
                list.add(dto);
            }

            // 按照状态显示进行中 → 未开始 → 已结束
            List<ProductSecKillListDTO> startList = list.stream().filter(dto -> ProductActivityStatusEnum.getActivityStatusEnum(dto.getStatus()) == ProductActivityStatusEnum.STARTED).collect(Collectors.toList());
            List<ProductSecKillListDTO> unStartList = list.stream().filter(dto -> ProductActivityStatusEnum.getActivityStatusEnum(dto.getStatus()) == ProductActivityStatusEnum.UN_START).collect(Collectors.toList());
            List<ProductSecKillListDTO> completeList = list.stream().filter(dto -> ProductActivityStatusEnum.getActivityStatusEnum(dto.getStatus()) == ProductActivityStatusEnum.COMPLETED).collect(Collectors.toList());

            List<ProductSecKillListDTO> data = new ArrayList<>();
            data.addAll(startList);
            data.addAll(unStartList);
            data.addAll(completeList);
            dtoPager.setData(data);
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(dtoPager));
    }

    /**
     * 秒杀产品详情
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/2/17 21:42
     */
    @GetMapping(value = "/detail")
    public void detailSecKill(HttpServletResponse response, @RequestParam("secKillId") int secKillId) {
        ProductSecKill secKill = productSecKillService.get(secKillId);
        if(secKill==null|| !secKill.isEnabled()){
            throw new ServiceResponseException(SysError.PARAM_ERROR,"不存在的秒杀产品!");
        }
        Product product = productService.get(secKill.getProductId());
        ProductSku sku = productSkuService.getSku(secKill.getProductId(), secKill.getSn());
        ProductSecKillFormDTO formDTO = new ProductSecKillFormDTO();
        BeanUtils.copyProperties(secKill, formDTO);

        JSONObject json = JsonUtil.toJsonFilter(formDTO);
        ProductTxt txt = product.getTxt();
        List<ProductAttr> attrs = product.getAttrs();
        List<ProductAttrDTO> attrDTOS = new ArrayList<>();
        if (attrs != null) {
            attrs.forEach(productAttr -> {
                ProductAttrDTO dto = new ProductAttrDTO();
                BeanUtils.copyProperties(productAttr, dto);
                attrDTOS.add(dto);
            });
        }

        json.put("status",secKill.getStatus());
        json.put("originalPrice", sku.getOriginalPrice());
        json.put("remark", txt == null ? "" : txt.getRemark());
        json.put("attrs", attrDTOS);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(json));
    }
}